// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
    const { sessionId, user1, user2, goodsId } = event;
  
    const now = new Date().toISOString();
    
    try {
      // 创建新会话
      await db.collection('chat_sessions').add({
        data: {
          _id: sessionId,
          users: [user1, user2],
          goodsId: goodsId, // 关联的商品ID
          lastMessage: {
            content: `关于商品的咨询`,
            type: 'text',
            sender: user1,
            time: now
          },
          unreadCount: {
            [user1]: 0,
            [user2]: 0
          },
          createTime: now
        }
      });
      
      return { success: true, message: '会话创建成功' };
    } catch (e) {
      console.error('创建会话失败', e);
      return { success: false, message: '会话创建失败' };
    }
  };